﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CivilleWP7.Civille.Source;
using System.Data.Services.Client;
using CivilleWP7.CivilleDataServiceReference;
using CivilleWP7.Views.Controls;
using SL.Phone.Federation.Utilities;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;

namespace CivilleWP7.Views.Pages
{
    public partial class ExtrasPivotPage : PhoneApplicationPage
    {
        private List<Bonu> AllBonuses = new List<Bonu>();
        private List<Achievement> AllAchievements = new List<Achievement>();
        private List<Reward> AllRewards = new List<Reward>();
        private List<int> CompletedBonuses = new List<int>();
        private List<int> CompletedAchievements = new List<int>();
        private List<int> CompletedRewards = new List<int>();
        private bool IsLightTheme;

        public ExtrasPivotPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ExtrasPivotPage_Loaded);
            
            setBackground();
        }
        void checkThemeColor()
        {
            var visibility = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
            if (visibility == Visibility.Visible)
                IsLightTheme = true;
            else
                IsLightTheme = false;
        }
        void setBackground()
        {
            checkThemeColor();
            ImageBrush myBrush = new ImageBrush();
            if(IsLightTheme)
                myBrush.ImageSource=new BitmapImage(new Uri("/Resources/Images/Backgroundwhite.jpg",UriKind.Relative));
            else
                myBrush.ImageSource = new BitmapImage(new Uri("/Resources/Images/Background.jpg",UriKind.Relative));
            ContentPanel.Background=myBrush;
        }
        void ExtrasPivotPage_Loaded(object sender, RoutedEventArgs e)
        {
            AllBonuses.Clear();
            AllAchievements.Clear();
            AllRewards.Clear();
            CompletedBonuses.Clear();
            CompletedAchievements.Clear();
            CompletedRewards.Clear();
            AchievementsListBox.Items.Clear();
            BonusesListBox.Items.Clear();
            RewardsListBox.Items.Clear();
            TaskHistoryList.Items.Clear();

            PageTitle.Text = UserContext.CurrentUser.FirstName;


            CivilleDataServiceConnector.SetLevelQueryParameters(UserContext.CurrentUser.CurrentLevel);
            CivilleDataServiceConnector.LevelQuery.BeginExecute(OnLevelQueryCompleted, CivilleDataServiceConnector.LevelQuery);

            CivilleDataServiceConnector.SetGetAllBonusesQueryParameters();
            CivilleDataServiceConnector.GetAllBonusesQuery.BeginExecute(OnGetAllBonusesCompleted, CivilleDataServiceConnector.GetAllBonusesQuery);
            CivilleDataServiceConnector.SetGetAllAchievementsParameters();
            CivilleDataServiceConnector.GetAllAchievementsQuery.BeginExecute(OnGetAllAchievementsCompleted, CivilleDataServiceConnector.GetAllAchievementsQuery);
            CivilleDataServiceConnector.SetGetAllRewardsParamenters();
            CivilleDataServiceConnector.GetAllRewardsQuery.BeginExecute(OnGetAllRewardsCompleted, CivilleDataServiceConnector.GetAllRewardsQuery);
            CivilleDataServiceConnector.AllTasksQuery.BeginExecute(OnGetAllTasksCompleted, CivilleDataServiceConnector.AllTasksQuery);
        }

        private void OnLevelQueryCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<Level> query = result.AsyncState as DataServiceQuery<Level>;
                    Level lvl = query.EndExecute(result).First();

                    //UserLevelControl.LevelProgressBar.Minimum = 0;
                    UserLevelControl.LevelProgressBar.Value = ((UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints) / (double)lvl.Points) * 100;
                    UserLevelControl.LevelProgressBar2.Value = ((UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints) / (double)lvl.Points) * 100;
                    UserLevelControl.LevelProgressBar3.Value = ((UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints) / (double)lvl.Points) * 100;
                    
                    //UserLevelControl.LevelProgressBar.Maximum = lvl.Points;
                    UserLevelControl.MaxPointsTextBlock.Text = lvl.Points.ToString();
                    UserLevelControl.NrPointsTextBlock.Text = (UserContext.CurrentUser.Points - UserContext.CurrentUser.LastLevelPoints).ToString();
                    UserLevelControl.MinPointsTextBlock.Text = "0";
                    UserLevelControl.LevelTextBlock.Text ="Level: " + lvl.ID;

                    CarbonTasksTxt.Text = "Carbon Tasks - " + UserContext.CurrentUser.CarbonType.ToString() + "/" + lvl.CarbonType.ToString() + " | Diamond Tasks - " + UserContext.CurrentUser.DiamondType.ToString() + "/" + lvl.DiamondType.ToString(); ;
                });
        }

        private void OnGetAllBonusesCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<Bonu> query = result.AsyncState as DataServiceQuery<Bonu>;
                    foreach (Bonu bonus in query.EndExecute(result))
                    {
                        AllBonuses.Add(bonus);
                    }
                    CivilleDataServiceConnector.SetGetCompletedBonusesQueryParameters();
                    CivilleDataServiceConnector.GetCompletedBonusesQuery.BeginExecute(OnGetCompletedBonusesCompleted, CivilleDataServiceConnector.GetCompletedBonusesQuery);
                });
        }

        private void OnGetAllAchievementsCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<Achievement> query = result.AsyncState as DataServiceQuery<Achievement>;
                    foreach (Achievement achievement in query.EndExecute(result))
                    {
                        AllAchievements.Add(achievement);
                    }
                    CivilleDataServiceConnector.SetGetCompletedAchievementsParameters();
                    CivilleDataServiceConnector.GetCompletedAchievementsQuery.BeginExecute(OnGetCompletedAchievementsCompleted, CivilleDataServiceConnector.GetCompletedAchievementsQuery);
                });
        }

        private void OnGetAllRewardsCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<Reward> query = result.AsyncState as DataServiceQuery<Reward>;
                    foreach (Reward reward in query.EndExecute(result))
                    {
                        AllRewards.Add(reward);
                    }
                    CivilleDataServiceConnector.SetGetCompletedRewardsParamenters();
                    CivilleDataServiceConnector.GetCompletedRewardsQuery.BeginExecute(OnGetCompletedRewardsCompleted, CivilleDataServiceConnector.GetCompletedRewardsQuery);
                });
        }

        private void OnGetCompletedBonusesCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                DataServiceQuery<CivilleUserToBonu> query = result.AsyncState as DataServiceQuery<CivilleUserToBonu>;
                foreach (CivilleUserToBonu bonus in query.EndExecute(result))
                {
                    CompletedBonuses.Add(bonus.BonusID);
                }

                foreach (Bonu bonus in AllBonuses)
                {
                    if (CompletedBonuses.Contains(bonus.ID))
                    {
                        CustomListItem listItem = new CustomListItem();
                        listItem.TitleTxt.Text = bonus.Title;
                        listItem.DescriptionTxt.Text = bonus.Description;
                        listItem.CheckMarkImage.Source = new BitmapImage(new Uri("/CivilleWP7;component/Resources/Images/check.png", UriKind.Relative));
                        listItem.CheckMarkImage.Width = 50;
                        BonusesListBox.Items.Add(listItem);
                    }
                }
                foreach (Bonu bonus in AllBonuses)
                {
                    if (!CompletedBonuses.Contains(bonus.ID))
                    {
                        CustomListItem listItem = new CustomListItem();
                        listItem.TitleTxt.Text = bonus.Title;
                        listItem.DescriptionTxt.Text = bonus.Description;
                        BonusesListBox.Items.Add(listItem);
                    }
                }
            });
        }

        private void OnGetCompletedAchievementsCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<CivilleUserToAchievement> query = result.AsyncState as DataServiceQuery<CivilleUserToAchievement>;
                    foreach (CivilleUserToAchievement achievement in query.EndExecute(result))
                    {
                        CompletedAchievements.Add(achievement.AchievementID);
                    }

                    foreach (Achievement achievement in AllAchievements)
                    {
                        if (CompletedAchievements.Contains(achievement.ID))
                        {
                            CustomListItem listItem = new CustomListItem();
                            listItem.TitleTxt.Text = achievement.Title;
                            listItem.DescriptionTxt.Text = achievement.Description;
                            listItem.CheckMarkImage.Source = new BitmapImage(new Uri("/CivilleWP7;component/Resources/Images/check.png", UriKind.Relative));
                            listItem.CheckMarkImage.Width = 50;
                            AchievementsListBox.Items.Add(listItem);
                        }
                    }
                    foreach (Achievement achievement in AllAchievements)
                    {
                        if (!CompletedAchievements.Contains(achievement.ID))
                        {
                            CustomListItem listItem = new CustomListItem();
                            listItem.TitleTxt.Text = achievement.Title;
                            listItem.DescriptionTxt.Text = achievement.Description;
                            AchievementsListBox.Items.Add(listItem);
                        }
                    }
                });
        }

        private void OnGetCompletedRewardsCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                {
                    DataServiceQuery<CivilleUserToReward> query = result.AsyncState as DataServiceQuery<CivilleUserToReward>;
                    foreach (CivilleUserToReward reward in query.EndExecute(result))
                    {
                        CompletedRewards.Add(reward.RewardID);
                    }
                    foreach (Reward reward in AllRewards)
                    {
                        if (CompletedRewards.Contains(reward.ID))
                        {
                            CustomListItem listItem = new CustomListItem();
                            listItem.TitleTxt.Text = reward.Title;
                            listItem.DescriptionTxt.Text = reward.Description;
                            listItem.CheckMarkImage.Source = new BitmapImage(new Uri("/CivilleWP7;component/Resources/Images/check.png", UriKind.Relative));
                            listItem.CheckMarkImage.Width = 50;
                            listItem.ID = reward.ID;
                            listItem.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(listItem_Tap);
                            RewardsListBox.Items.Add(listItem);
                        }
                    }
                    foreach (Reward reward in AllRewards)
                    {
                        if (!CompletedRewards.Contains(reward.ID))
                        {
                            CustomListItem listItem = new CustomListItem();
                            listItem.TitleTxt.Text = reward.Title;
                            listItem.DescriptionTxt.Text = reward.Description;
                            RewardsListBox.Items.Add(listItem);
                        }
                    }
                });
        }

        void listItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            CustomListItem listItem = sender as CustomListItem;
            foreach (Reward r in AllRewards)
            {
                if (r.ID == listItem.ID)
                {
                    GetReward.TheReward = r;
                    NavigationService.Navigate(new Uri("/Views/Pages/GetReward.xaml", UriKind.Relative));
                }
            }
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to log out?", "Log out", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                RequestSecurityTokenResponseStore _rstrStore = App.Current.Resources["rstrStore"] as RequestSecurityTokenResponseStore;
                _rstrStore.RequestSecurityTokenResponse = null;
                NavigationService.Navigate(new Uri("/Views/Pages/SelectAuthPage.xaml", UriKind.Relative));
            }
        }

        private void OnGetAllTasksCompleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                List<Task> AllTasks = new List<Task>();
                DataServiceQuery<Task> query = result.AsyncState as DataServiceQuery<Task>;
                AllTasks = query.EndExecute(result).ToList();

                CivilleDataServiceConnector.SetTaskHistoryParameters(UserContext.CurrentUser.ID);
                CivilleDataServiceConnector.GetTaskHistory.BeginExecute((result2) =>
                {

                    Dispatcher.BeginInvoke(() =>
                    {
                        DataServiceQuery<TaskHistory> query2 = result2.AsyncState as DataServiceQuery<TaskHistory>;
                        foreach (TaskHistory history in query2.EndExecute(result2))
                        {
                            Task t = AllTasks.Where(x => x.ID == history.TaskID).First();
                            CustomListItem listItem = new CustomListItem();
                            listItem.TitleTxt.Text = t.Title;
                            listItem.DescriptionTxt.Text = t.Description;
                            listItem.CheckMarkImage.Source = new BitmapImage(new Uri(t.Logo, UriKind.RelativeOrAbsolute));
                            listItem.CheckMarkImage.Width = 50;
                            TaskHistoryList.Items.Add(listItem);
                        }
                    });
                }, CivilleDataServiceConnector.GetTaskHistory);
            });
        }
    }
}
